export class EventMgr
{
    private static m_instance:EventMgr;
    private listeners:any;

    private constructor()
    {
        this.listeners = {};
    }

    static get Instance()
    {
        if (EventMgr.m_instance == null) {
            EventMgr.m_instance = new EventMgr();
        }
        return EventMgr.m_instance;
    }

    emit(event:Event_Name, ...params:any[])
    {
        let cbs:any[] = this.listeners[event];
        if(!cbs)
        {
            return;
        }
        for(let i:number = 0, len:number = cbs.length; i < len; i += 2)
        {
            let cb:any = cbs[i];
            let host:any = cbs[i+1];
            cb.call(host, ...params);
        }
    }

    on(event:Event_Name, cb:Function, host:any = null)
    {
        let cbs:any[] = this.listeners[event];
        if(!cbs)
        {
            this.listeners[event] = cbs = []; 
        }
        cbs.push(cb, host);
    }

    off(event:Event_Name, cb:Function)
    {
        let cbs:any[] = this.listeners[event];
        if(!cbs)
        {
            return;
        }
        let index:number = cbs.indexOf(cb);
        if(index < 0)
        {
            cc.warn("EventMgr remove", event, ", but cb not exists!");
            return;
        }
        cbs.splice(index, 2);
    }

    clear()
    {
        for(let key in this.listeners)
        {
            this.listeners[key].length = 0;
        }
        this.listeners = {};
    }
}

/**事件名称定义*/
export enum Event_Name {
    USER_INFO_CHANGED,
    FORMATION_CHANGED,
    MONEY_CHANGED,
    PLAYERLIST_CHANGED,
    SALE_PLAYER,
    ZHANLI_CHANGED,
    UI_SHOW,
    UI_HIDE,
    MUTE_MUSIC,
    UNMUTE_MUSIC,
}